package cn.wyh.security.filter;

import cn.wyh.security.entity.SecurityUser;
import cn.wyh.security.entity.User;
import cn.wyh.security.security.TokenManager;
import cn.wyh.utils.R;
import cn.wyh.utils.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;


import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author wyh
 * @version 1.0
 * @date 2021/10/4 23:17
 */

public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private RedisTemplate redisTemplate;
    private TokenManager tokenManager;
    private AuthenticationManager authenticationManager;

    public TokenLoginFilter(RedisTemplate redisTemplate, TokenManager tokenManager, AuthenticationManager authenticationManager) {
        this.redisTemplate = redisTemplate;
        this.tokenManager = tokenManager;
        this.authenticationManager = authenticationManager;
        this.setPostOnly(false); //关闭仅post请求
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login","POST")); //使登录路径设置为post提交
    }

    /**
     * 获得表单的用户名密码进行登录认证
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        try {
            User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
            return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword()
                    ,new ArrayList<>())); //会根据userDetailsService去访问数据库
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }


    }

    //登录成功
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        //从attemptAuthentication中获取主要信息
        SecurityUser principalUser = (SecurityUser) authResult.getPrincipal();
        //获得token
        String token = tokenManager.createToken(principalUser.getCurrentUserInfo().getUsername());
        //保存权限到redis中
        redisTemplate.opsForValue().set(principalUser.getCurrentUserInfo().getUsername(),principalUser.getPermissionValueList());
        //返回响应参数
        ResponseUtil.out(response, R.ok().data("token",token));
    }

    //登录失败
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        //返回响应参数
        ResponseUtil.out(response, R.error());
    }
}
